#include "main.h"

void query(int newfd,MSG* pmsg)
{
	char* logintime;

	/*打开词典数据库*/
	sqlite3_open("dict.db",&pdb);

	/*检验客户端是否要退出*/
	if(strncmp(pmsg->info,"##",2) == 0)
			goto CLOSE;

	/*查询客户端发来的单词*/
	printf(">>Query word:\n%s\n",pmsg->info);
	snprintf(sql,size,"select comment from dicts \
		where word = '%s';",pmsg->info);
	sqlite3_get_table(pdb,sql, &result, &row, &col, &errmsg);

	if(row > 0)
	{
		/*添加历史记录*/
		sqlite3_open("user.db",&pdb);
		gettime(&logintime);
		snprintf(sql,size,"insert into history values('%s','%s','%s');",pmsg->username,pmsg->info,logintime);
		sqlite3_exec(pdb, sql, NULL, NULL, &errmsg);	
		sqlite3_close(pdb);

		/*存储并打印查询结果*/
		printf(">>Query result:\n");
		strcpy(pmsg->info,result[1]);
		printf("%s\n",pmsg->info);
	}				
	else
	{
		strcpy(pmsg->info,"Can't find the word.");
		printf("%s\n",pmsg->info);
	}
	
	/*返回查询结果*/
	write(newfd,pmsg,sizeof(MSG));

	/*释放查询结果*/
	sqlite3_free_table(result);

	CLOSE:
	/*关闭词典数据库*/
	sqlite3_close(pdb);
}

void history(int newfd,MSG* pmsg)
{
	int i,j;

	/*打开用户数据库*/
	sqlite3_open("user.db",&pdb);

	/*查询用户历史记录*/
	snprintf(sql,size,"select * from history \
		where username = '%s';",pmsg->username);
	sqlite3_get_table(pdb,sql, &result, &row, &col, &errmsg);

	/*返回查询结果*/
	for (i = 0; i < row + 1; i++)
	{
		for(j = 0; j < col; j++)
		{
			strncpy(pmsg->info, *(result++),size);
			write(newfd, pmsg, sizeof(MSG));
			usleep(1000);
		}
	}

	/*告诉客户端发送完毕*/
	strncpy(pmsg->info,"OVER",size);
	write(newfd, pmsg, sizeof(MSG));
	printf("Query history over.\n");

	/*释放查询结果*/
	//sqlite3_free_table(result);

	/*关闭词典数据库*/
	sqlite3_close(pdb);
}

